import os
import json
import shutil
from datetime import datetime

class ResultManager:
    def __init__(self, base_path):
        self.base_path = base_path
        self.results_dir = os.path.join(base_path, 'results')
        os.makedirs(self.results_dir, exist_ok=True)
        
    def save_batch_result(self, results, config):
        # 创建新的结果目录
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        batch_dir = os.path.join(self.results_dir, f'batch_{timestamp}')
        os.makedirs(batch_dir)
        
        # 保存处理后的图片
        images_dir = os.path.join(batch_dir, 'images')
        os.makedirs(images_dir)
        
        for result in results:
            # 复制原始图片和处理后的图片
            shutil.copy2(result['original_path'], 
                        os.path.join(images_dir, f"original_{result['filename']}"))
            shutil.copy2(result['normalized_path'],
                        os.path.join(images_dir, f"normalized_{result['filename']}"))
        
        # 保存处理结果和配置信息
        with open(os.path.join(batch_dir, 'results.json'), 'w', encoding='utf-8') as f:
            json.dump({
                'timestamp': timestamp,
                'config': config.to_dict(),
                'results': results
            }, f, ensure_ascii=False, indent=2)
        
        return batch_dir
    
    def get_batch_results(self):
        results = []
        for batch_dir in os.listdir(self.results_dir):
            result_file = os.path.join(self.results_dir, batch_dir, 'results.json')
            if os.path.exists(result_file):
                with open(result_file, 'r', encoding='utf-8') as f:
                    results.append(json.load(f))
        return sorted(results, key=lambda x: x['timestamp'], reverse=True) 